package com.boost.tjvm.asm;

import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

/**
 * Created by cai.tian on 2017/4/24.
 */
public class AsmClassLoad extends ClassLoader {

    public AsmClassLoad(){
        super(AsmClassLoad.class.getClassLoader());
    }

   /* private String className="DsfAdapter";
    private String packageName="com.huawei.cgw.paymenthub.dsfadapter.adapter.";*/
    private String className="TestClass";
    private String packageName="com.boost.tjvm.remote.";

    private static final int INPUT_STREAM_DATA_CHUNK_SIZE = 4096;

    private Class getModf(String name) throws IOException {
        URL resource = getResource(name);
        ClassReader classReader = new ClassReader(resource.openStream());
        ClassWriter classWriter = new ClassWriter(classReader, ClassWriter.COMPUTE_MAXS);
        ClassVisitor cv = new MethodChangeClassAdapter(classWriter);
        classReader.accept(cv, ClassReader.SKIP_DEBUG);
        byte[] classFile = classWriter.toByteArray();
        return defineClass(packageName+className, classFile, 0, classFile.length);
    }


    protected Class<?> loadClass(String name, boolean resolve)
            throws ClassNotFoundException {
        if (!(packageName+className).equals(name)) {
            return super.loadClass(name, resolve);
        }
        synchronized (getClassLoadingLock(name)) {
            try {
                return getModf(packageName.replaceAll("\\.","/") + className +".class");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }


    private static byte[] readStream(final InputStream inputStream, final boolean close)
            throws IOException {
        if (inputStream == null) {
            throw new IOException("Class not found");
        }
        try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
            byte[] data = new byte[INPUT_STREAM_DATA_CHUNK_SIZE];
            int bytesRead;
            while ((bytesRead = inputStream.read(data, 0, data.length)) != -1) {
                outputStream.write(data, 0, bytesRead);
            }
            outputStream.flush();
            return outputStream.toByteArray();
        } finally {
            if (close) {
                inputStream.close();
            }
        }
    }

}